package com.business.dashboard.controller;

import com.business.dashboard.service.AdminUserService;
import com.business.dashboard.service.UserService;
import com.business.dashboard.service.NewsArticleService;
import com.business.dashboard.service.BusinessPlanService;
import com.business.dashboard.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 管理后台统计数据控制器
 * 
 * @author Claude
 * @since 2025-07-06
 */
@Slf4j
@RestController
@RequestMapping("/api/admin/stats")
public class AdminStatsController {

    @Autowired
    private UserService userService;

    @Autowired
    private AdminUserService adminUserService;

    @Autowired
    private NewsArticleService newsArticleService;

    @Autowired
    private BusinessPlanService businessPlanService;

    /**
     * 获取仪表板统计数据
     */
    @GetMapping("/overview")
    public ResultUtil<Map<String, Object>> getDashboardStats() {
        try {
            Map<String, Object> stats = new HashMap<>();
            
            // 用户统计
            long totalUsers = userService.getUserCount();
            stats.put("totalUsers", totalUsers);
            
            // 活跃用户（状态为1的用户）
            long activeUsers = userService.getActiveUserCount();
            stats.put("activeUsers", activeUsers);
            
            // 文章统计
            long totalNews = newsArticleService.getNewsCount();
            stats.put("totalNews", totalNews);
            
            // 商业计划书统计
            long totalPlans = businessPlanService.getBusinessPlanCount();
            stats.put("totalPlans", totalPlans);
            
            // 今日新增用户
            long todayRegistrations = userService.getTodayRegistrationCount();
            stats.put("todayRegistrations", todayRegistrations);
            
            // 今日登录用户数
            long todayLogins = userService.getTodayLoginCount();
            stats.put("todayLogins", todayLogins);
            
            log.info("管理员获取统计数据，");
            return ResultUtil.success("获取统计数据成功", stats);
        } catch (Exception e) {
            log.error("获取统计数据失败，", e);
            return ResultUtil.error("获取统计数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户增长趋势数据
     */
    @GetMapping("/user-growth")
    public ResultUtil<Map<String, Object>> getUserGrowthStats() {
        try {
            Map<String, Object> growthData = new HashMap<>();
            
            // TODO: 实现用户增长趋势统计
            growthData.put("labels", new String[]{"1月", "2月", "3月", "4月", "5月", "6月"});
            growthData.put("data", new int[]{10, 20, 30, 25, 40, 50});
            
            return ResultUtil.success("获取用户增长数据成功", growthData);
        } catch (Exception e) {
            log.error("获取用户增长数据失败，", e);
            return ResultUtil.error("获取用户增长数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取最近登录用户
     */
    @GetMapping("/recent-users")
    public ResultUtil<Object> getRecentUsers(
                                           @RequestParam(defaultValue = "10") Integer limit) {
        try {
            Object recentUsers = userService.getRecentUsers(limit);
            return ResultUtil.success("获取最近用户成功", recentUsers);
        } catch (Exception e) {
            log.error("获取最近用户失败，", e);
            return ResultUtil.error("获取最近用户失败：" + e.getMessage());
        }
    }

    /**
     * 获取系统健康状态
     */
    @GetMapping("/health")
    public ResultUtil<Map<String, Object>> getSystemHealth() {
        try {
            Map<String, Object> health = new HashMap<>();
            
            // 数据库连接状态
            health.put("database", "健康");
            
            // 系统运行时间
            long uptime = System.currentTimeMillis() - getApplicationStartTime();
            health.put("uptime", uptime);
            
            // 内存使用情况
            Runtime runtime = Runtime.getRuntime();
            Map<String, Object> memory = new HashMap<>();
            memory.put("total", runtime.totalMemory());
            memory.put("free", runtime.freeMemory());
            memory.put("used", runtime.totalMemory() - runtime.freeMemory());
            health.put("memory", memory);
            
            return ResultUtil.success("获取系统健康状态成功", health);
        } catch (Exception e) {
            log.error("获取系统健康状态失败，", e);
            return ResultUtil.error("获取系统健康状态失败：" + e.getMessage());
        }
    }

    /**
     * 获取应用启动时间（简化实现）
     */
    private long getApplicationStartTime() {
        // 简化实现，实际应该从应用上下文获取
        return System.currentTimeMillis() - 3600000; // 假设运行了1小时
    }

}